﻿using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using Bookvar.ObjectModel;

namespace Bookvar.UI
{
    /// <summary>
    /// Interaction logic for NotesButton.xaml
    /// </summary>
    public partial class NotesButton
    {
        public static readonly DependencyProperty TopicProperty =
            DependencyProperty.Register( "Topic", typeof( Topic ), typeof( NotesButton ),
                                         new FrameworkPropertyMetadata( default( Topic ), TopicPropertyChanged ) );

        public Topic Topic
        {
            get { return (Topic) GetValue( TopicProperty ); }
            set { SetValue( TopicProperty, value ); }
        }

        public static void TopicPropertyChanged( DependencyObject element, DependencyPropertyChangedEventArgs args )
        {
            NotesButton button = (NotesButton) element;

            Topic oldTopic = args.OldValue as Topic;
            if ( oldTopic != null )
            {
                oldTopic.PropertyChanged -= button.OnTopicPropertyChanged;
            }
            Topic newTopic = args.NewValue as Topic;
            if ( newTopic != null )
            {
                newTopic.PropertyChanged += button.OnTopicPropertyChanged;
                button.Text = newTopic.Note;
                button.btnShowNotes.CommandParameter = newTopic; 
            }
        }

        public NotesButton()
        {
            InitializeComponent();
        }

        private void OnTopicPropertyChanged( object sender, PropertyChangedEventArgs e )
        {
            if ( e.PropertyName == "Note" )
            {
                Text = Topic.Note;
            }
        }

        private TextRange Text
        {
            set
            {
                if ( value != null )
                {
                    using ( MemoryStream stream = new MemoryStream() )
                    {
                        value.Save( stream, DataFormats.XamlPackage );
                        TextRange topicNotes =
                            new TextRange( toolTipBox.Document.ContentStart, toolTipBox.Document.ContentEnd );
                        topicNotes.Load( stream, DataFormats.XamlPackage );
                    }
                }
            }
        }
    }
}